package com.chanceit.ssss.dialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.GlobalVariable;
import org.gl.customview.PullToRefreshView;
import org.gl.customview.PullToRefreshView.OnFooterRefreshListener;
import org.gl.customview.PullToRefreshView.OnHeaderRefreshListener;
import org.gl.utils.Tip;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.data.DataSources;
import com.chanceit.ssss.fragments.BaseFragment.webkey;

public class CarTypeSpinnerDialog extends AlertDialog implements
		OnClickListener, android.content.DialogInterface.OnClickListener,
		OnHeaderRefreshListener, OnFooterRefreshListener {

	AlertDialog AlertDialog;
	private ListView listView;
	private Context themeContext;
	int page;
	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();
	String[] keys = new String[] { "brand", "carId", "carName", "", "" };
	// String[] keys = new String[] { "brand", "carId", "carName", "brandImage",
	// "" };
	PullToRefreshView mPullToRefreshView;
	protected JSONArray userListJosnAry = new JSONArray();
//	private String brand;
	private String companyId;

	public CarTypeSpinnerDialog(Context context, final EditText editView) {
		super(context, 0);
		themeContext = context;
		// setButton(BUTTON_POSITIVE, "ok", this);
		setIcon(0);
		companyId = GlobalVariable.UserInfo.optJSONObject("company").optString(
				"companyId");//2013-11-13 获取车型列表的接口参数修改
//		brand = GlobalVariable.UserInfo.optJSONObject("company").optString(
//				"brand");
//		if (brand.equals("null")) {
//			brand = null;
//		}
		if (companyId.equals("null")) {
			companyId = null;
		}
		LayoutInflater inflater = (LayoutInflater) themeContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.order_carer_list, null);
		view.setBackgroundColor(0xFFE7EBEE);
		listView = (ListView) view.findViewById(R.id.order_carer_lv);
		mPullToRefreshView = (PullToRefreshView) (view
				.findViewById(R.id.main_pull_refresh_view));
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					editView.setTag(userListJosnAry.getJSONObject(position)
							.optInt("carId"));
					editView.setText(""
							+ userListJosnAry.getJSONObject(position)
									.optString("carName"));
					dismiss();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		setView(view);

		getData(null);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				if (TextUtils.isEmpty(companyId)) {

					// page++; FIXME 无分页 无更多
				} else {
					page = 1;
				}
//				if (TextUtils.isEmpty(brand)) {
//					
//					// page++; FIXME 无分页 无更多
//				} else {
//					page = 1;
//				}
				getData(page);
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page = 1;
				getData(null);
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}

	private void getData(Integer _page) {
		DataSources ds = new DataSources();

//		if (TextUtils.isEmpty(brand)) {
			if (TextUtils.isEmpty(companyId)) {
			ds.getCarList(_page, new AjaxCallBack<String>() {
				private SimpleAdapter adapter;

				public void onLoading(long count, long current) {
				}

				public void onSuccess(String t) {
					int code = 0;
					try {
						JSONObject result = new JSONObject(t);
						;
						code = result.optInt(webkey.code);
						JSONArray newJsonArray = result
								.optJSONArray(webkey.result);
						contents.removeAll(contents);
						if (page <= 1) {// 如果当前页码为<=1 说明是第一次加载 清楚以前的旧数据
							userListJosnAry = null;
							userListJosnAry = newJsonArray;
						} else {// 否则就是加载更多的分页数据,把新的数据添加到集合中
							for (int i = 0; i < newJsonArray.length(); i++) {
								userListJosnAry.put(newJsonArray.opt(i));
							}
						}
						if (userListJosnAry == null) {
							userListJosnAry = new JSONArray();
						}
						int count = userListJosnAry.length();
						for (int i = 0; i < count; i++) {
							Map<String, Object> map = new HashMap<String, Object>();
							JSONObject temp = userListJosnAry.getJSONObject(i);
							for (String key : keys) {
								Object o = temp.opt(key);
								if (o == null || o.toString().equals("null")) {
									o = "";
								}
								map.put(key, o.toString());// FIXME brandImage
							}
							contents.add(map);
						}
						if (adapter == null) {
							if (contents.size() > 0) {
								adapter = new SimpleAdapter(
										themeContext,
										(List<Map<String, Object>>) contents,
										R.layout.list_item_carer,
										keys,
										new int[] { R.id.textView1,
												R.id.textView2, R.id.textView3,
												R.id.textView4, R.id.textView5 });
								listView.setAdapter(adapter);
							}
						} else {
							adapter.notifyDataSetChanged();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					} finally {
						page--;
						if (code != 0) {
							Tip.show("load car info fail");
						} else {
							page++;
						}
					}

				}
			});
		} else {

//			ds.getCarListByBrand(_page, brand, new AjaxCallBack<String>() {
				ds.getCarListByBrand(_page, companyId, new AjaxCallBack<String>() {
				private SimpleAdapter adapter;

				public void onLoading(long count, long current) {
				}

				public void onSuccess(String t) {
					int code = 0;
					try {
						// JSONObject result = new JSONObject(t);
						// ;
						// code = result.optInt(webkey.code);
						// JSONArray newJsonArray =
						// result.optJSONArray(webkey.result);
						// contents.removeAll(contents);
						// if (page <= 1) {// 如果当前页码为<=1 说明是第一次加载 清楚以前的旧数据
						// userListJosnAry = null;
						// userListJosnAry = newJsonArray;
						// } else {// 否则就是加载更多的分页数据,把新的数据添加到集合中
						// for (int i = 0; i < newJsonArray.length(); i++) {
						// userListJosnAry.put(newJsonArray.opt(i));
						// }
						// }
						// if (userListJosnAry == null) {
						// userListJosnAry = new JSONArray();
						// }
						// int count = userListJosnAry.length();
						// for (int i = 0; i < count; i++) {
						// Map<String, Object> map = new HashMap<String,
						// Object>();
						// JSONObject temp = userListJosnAry.getJSONObject(i);
						// for (String key : keys) {
						// Object o = temp.opt(key);
						// if (o == null || o.toString().equals("null")) {
						// o = "";
						// }
						// map.put(key, o.toString());//FIXME brandImage
						// }
						// contents.add(map);
						// }
						// if (adapter == null) {
						// if (contents.size() > 0) {
						// adapter = new SimpleAdapter(themeContext,
						// (List<Map<String, Object>>) contents,
						// R.layout.list_item_carer, keys, new int[] {
						// R.id.textView1, R.id.textView2,
						// R.id.textView3, R.id.textView4,
						// R.id.textView5 });
						// listView.setAdapter(adapter);
						// }
						// } else {
						// adapter.notifyDataSetChanged();
						// }
						JSONArray newJsonArray = new JSONArray(t);
						contents.removeAll(contents);
						if (page <= 1) {// 如果当前页码为<=1 说明是第一次加载 清楚以前的旧数据
							userListJosnAry = null;
							userListJosnAry = newJsonArray;
						} else {// 否则就是加载更多的分页数据,把新的数据添加到集合中
							for (int i = 0; i < newJsonArray.length(); i++) {
								userListJosnAry.put(newJsonArray.opt(i));
							}
						}
						if (userListJosnAry == null) {
							userListJosnAry = new JSONArray();
						}
						int count = userListJosnAry.length();
						for (int i = 0; i < count; i++) {
							Map<String, Object> map = new HashMap<String, Object>();
							JSONObject temp = userListJosnAry.getJSONObject(i);
							for (String key : keys) {
								Object o = temp.opt(key);
								if (o == null || o.toString().equals("null")) {
									o = "";
								}
								map.put(key, o.toString());// FIXME brandImage
							}
							contents.add(map);
						}
						if (adapter == null) {
							if (contents.size() > 0) {
								adapter = new SimpleAdapter(
										themeContext,
										(List<Map<String, Object>>) contents,
										R.layout.list_item_carer,
										keys,
										new int[] { R.id.textView1,
												R.id.textView2, R.id.textView3,
												R.id.textView4, R.id.textView5 });
								listView.setAdapter(adapter);
							}
						} else {
							adapter.notifyDataSetChanged();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					} finally {
						page--;
						if (code != 0) {
							Tip.show("load car info fail");
						} else {
							page++;
						}
					}

				}
			});
		}
	}

	@Override
	public void onClick(View v) {
		showSpinner();
	}

	private void showSpinner() {
		this.show();

	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		dialog.dismiss();
	}
}
